package com.group.mall.controller;

import com.group.mall.common.Result;
import com.group.mall.domain.POJO.Cart;
import com.group.mall.domain.POJO.ShoppingCart;
import com.group.mall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * @Author：xiexu
 * @Date：2024/6/18 14:20
 */
@CrossOrigin
@Controller
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartService cartService;

    @GetMapping("/list/{userId}")
    public Result listCart(@PathVariable("userId") Integer userId){
        List<ShoppingCart> cartList = cartService.listCart(userId);
        return Result.success(cartList);
    }

    @PostMapping("/add")
    Result addCart(ShoppingCart cart){
        cart.setChecked("false");
        cart.setKindindex(0);
        cart.setCreateTime(LocalDate.now());
        return Result.success(cartService.addCart(cart));
    }

    @PostMapping("/findCart/{userId}")
    public Result getCartById(@PathVariable("userId") Integer userId){
        List<ShoppingCart> cartListById = cartService.getCartById(userId);
        return Result.success(cartListById);
    }

    @DeleteMapping("/delete/{cartId}/{userId}")
    public Result deleteCartById(@PathVariable("cartId") Integer cartId, @PathVariable("userId") Integer userId) {
        if(cartService.deleteCartById(cartId, userId)) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @PutMapping("/update")
    public Result updateCart(@RequestBody ShoppingCart cart) {
        if (cartService.updateCart(cart)) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }
}
